package com.example.mylock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * description: MyLock <br>
 * date: 2020/7/8 10:25 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
public class MyLock implements Lock {

    private boolean isHoldLock = false;

    private Thread holdLockThread = null;

    private int reentryLockCount = 0;

    @Override
    public synchronized void lock() {
        if (isHoldLock && Thread.currentThread() != holdLockThread){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        holdLockThread = Thread.currentThread();

        isHoldLock = true;
    }

    @Override
    public synchronized void unlock() {
        //判断当前线程是不是持有锁的线程，如果是 则重入次数-1 如果不是则不作处理
        if (Thread.currentThread() == holdLockThread){
            reentryLockCount--;

            if (reentryLockCount == 0){
                notify();
                isHoldLock = false;
            }
        }

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
